import {ModalForm, DrawerForm, ProFormSelect, ProFormText, ProFormUploadDragger, ProFormUploadButton, ProFormDependency, ProFormRadio} from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect, useState} from "react";
import {Form, message} from "antd";
import { firstValueFrom } from "rxjs"
import environment from "@/environment";
import { UploadProps } from "antd"
import { UploadChangeParam } from "antd/es/upload"
import { UploadRequestOption as RcCustomRequestOptions } from "rc-upload/lib/interface"

import IHelper from "@/services/helper.service";

type CreateFormProps = {
  name: string
  video: UploadProps['fileList']
  cover: UploadProps['fileList']
}

type IProps = {
  item: API.VideoItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
}

export default function VideoCreateForm({item, onCancel, onRefreshTable}: IProps) {
  const [form] = Form.useForm<CreateFormProps>();
  const open = Boolean(item)
  useEffect(() => {
    if (open) {
      form.setFieldsValue({
        name: item?.name, 
        cover: item?.cover ? [{uid: IHelper.hash(12), name: item.cover.split("/").pop(), url: IHelper.getServerAsset(item.cover), status: "done", response: {url: item.cover}}] : [],
        video: item?.video ? [{uid: IHelper.hash(12), name: item.video.split("/").pop(), url: IHelper.getServerAsset(item.video), status: "done", response: {url: item.video}}] : [],
      })
    }
  }, [open])
  function customRequest(opt: RcCustomRequestOptions) {
    const formData = new FormData()
    formData.append("file", opt.file)
    IHttp.uploadFile({data: formData, onUploadProgress(progressEvent) {
      opt.onProgress && opt.onProgress(progressEvent)
    },}).subscribe(
      res => {
        if (!res.status) {
          message.error(res.message || "Upload error.")
          opt.onError && opt.onError({name: "Upload error.", message: res.message || "Upload error."})
          return
        }
        opt.onSuccess && opt.onSuccess({url: res.data.url})
      }
    )
  }
  function uploadValueValidator(_rule: any, value: UploadProps['fileList'], callback: any) {
    if (!Array.isArray(value) || value.length <= 0) {
      callback(new Error("请上传文件"))
      return
    }
    if (value[0]?.status === "done" && !value[0]?.response?.url) {
      callback(new Error("请上传文件"))
      return
    }
    callback()
  }
  return (
    <DrawerForm<CreateFormProps>
      width={360}
      open={open}
      form={form}
      title={item?.id ? "编辑视频" : "新建视频"}
      onFinish={async (values) => {
        const postData = {
          name: values.name, 
          cover: values.cover?.[0]?.response?.url,
          video: values.video?.[0]?.response?.url,
          type: 1,
        }
        if (Object.values(postData).some(e => !e)) {
          message.error("信息不完整！")
          return
        }
        let res: IAxiosResponse | undefined = undefined
        if (item?.id) {
          res = await firstValueFrom(IHttp.updateVideo(item.id, postData))
        } else {
          res = await firstValueFrom(IHttp.createVideo(postData))
        }
        if (res?.status) {
          message.success(item?.id ?  "更新成功" : "创建成功")
          onRefreshTable()
        }
      }}
      drawerProps={{
        destroyOnClose: true,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <ProFormText
        name="name"
        label="名称"
        tooltip="最长为 24 位"
        placeholder="请输入名称"
        rules={[
          {required: true}
        ]}
      />
      <ProFormUploadButton
        label="上传封面"
        name={"cover"}
        rules={[{required: true, validator: uploadValueValidator, message: "请上传封面"}]}
        fieldProps={{
          multiple: false,
          name: "file",
          accept:"image/*",
          maxCount: 1,
          customRequest: customRequest,
        }}
      />
      <ProFormUploadButton 
        rules={[{required: true, validator: uploadValueValidator, message: "请上传视频"}]}
        label="上传视频"
        name={"video"}
        fieldProps={{
          multiple: false,
          name: "file",
          accept:"video/*",
          maxCount: 1,
          customRequest: customRequest,
        }}
      />
      
    </DrawerForm>
  )
}
